package com.buttonpay;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class MyProducts 
{ 
	Context mContext; 
	HttpConn httpConn=new HttpConn();
	String URL,checksumString,result;
	UserInfo userInfo;
	MD5Generator md5generator=new MD5Generator();
	Products[] products;
	ProgressDialog pd;
	Handler handler;
	
	ArrayList<String>
	
				    sysSerID,sysSerName,
					productID,productName,
					productDesc,productType,
					batchID,batchDesc,
					minVal,maxVal,ImageURL;
	
	private DataHelper dh;
	private ArrayList<Products> productList;
	
	public MyProducts(Context context, ProgressDialog pd, Handler handler) 
	{
		// TODO Auto-generated constructor stub
		this.mContext=context;
		this.pd=pd;
		this.handler=handler;
		userInfo=AppData.getUserInfo();
		this.dh = new DataHelper(context);
		productList=new ArrayList<Products>();
	}

	public void CheckProducts()
	{
		try
		{
					// TODO Auto-generated method stub
					boolean productsAvilable=getProductsFromDB();
					
					if(!productsAvilable)
					{
						//if no products avilable in database,then create new request and
						//store products to database
						System.out.println("==>No Products Avilable,creating new request.");
						
						result=createHttpConn();
						System.out.println("Result:"+result);
			
						if(result!=null)
						{
							productList=parseResult(result);
							addProductsToDB(productList);
							return;
						}
						else
						{
							handler.post(new Runnable()
							{
								public void run() 
								{
									pd.dismiss();
									Toast.makeText(mContext,"null response==>"+result,Toast.LENGTH_LONG).show();
								}
							});
							return;
						}
					}
					else
					{
						System.out.println("====>Products avilable in database..");
						return;
					} 
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return;
		}
		finally
		{
			dh.close();
		}
		
	}
		

	private void addProductsToDB(ArrayList<Products> productList) 
	{
		  
		for(Products p:productList)
		{
		    this.dh.insert(	 p.getSystemServiceID(),
			   		   		 p.getSystemServiceName(),
			   		   		 p.getProductID(),
			   		   		 p.getProductName(),
			   		   		 p.getProductDesc(),
			   		   		 p.getProductType(),
			   		   		 p.getBatchID(),
			   		   		 p.getminValue(),
			   		   		 p.getMaxValue(),
			   		   		 p.getImageURL());
		}
	} 

	private ArrayList<Products> parseResult(String data) 
	{
		 
			try
			{
				final JSONObject jsonObject=new JSONObject(data);
				JSONArray jsonArray;
				
				if(jsonObject.getString("ResponseCode").equals("000")&&jsonObject.getString("ResponseDescription").equals("Successfull"))
				{
					sysSerID=new ArrayList<String>();
					sysSerName=new ArrayList<String>();
					productID=new ArrayList<String>();
					productName=new ArrayList<String>();
					productDesc=new ArrayList<String>();
					productType=new ArrayList<String>();
					batchID=new ArrayList<String>();
					batchDesc=new ArrayList<String>();
					minVal=new ArrayList<String>();
					maxVal=new ArrayList<String>();
					ImageURL=new ArrayList<String>();
					if(jsonObject.has("SystemServiceID"))
					{
					     jsonArray=jsonObject.getJSONArray("SystemServiceID");
						  System.out.println("Length of systemserviceID:"+jsonArray.length()+
                                  "\ngetting System ServiceID");
						  for(int i=0;i<jsonArray.length();i++)
			                {
			                    sysSerID.add(jsonArray.getString(i));
			                }
					}
					
					if(jsonObject.has("SystemServiceName"))
		            {	
		                jsonArray=jsonObject.getJSONArray("SystemServiceName");
		                System.out.println("Length of SystemServiceName:"+jsonArray.length()+
		                                    "\ngetting System ServiceName");
		                for(int i=0;i<jsonArray.length();i++)
		                {
		                    sysSerName.add(jsonArray.getString(i));
		                }
		            }
					
					if(jsonObject.has("ProductID"))
		            {
		                jsonArray=jsonObject.getJSONArray("ProductID");
		                System.out.println("Length of ProductID:"+jsonArray.length()+
		                                    "\ngetting ProductID");
		                for(int i=0;i<jsonArray.length();i++)
		                {
		                    productID.add(jsonArray.getString(i));
		                }
		            }
				
				    if(jsonObject.has("ProductDescription"))
		            {
		                 jsonArray=jsonObject.getJSONArray("ProductDescription");
		                 System.out.println("Length of ProductDescription:"+jsonArray.length()+
		                                    "\ngetting ProductDescription");
		                 for(int i=0;i<jsonArray.length();i++)
		                 {
		                     productDesc.add(jsonArray.getString(i));
		                 } 
		            }
				   
				   if(jsonObject.has("BatchID"))
		            {
		               jsonArray = jsonObject.getJSONArray("BatchID");
		               System.out.println("length of BatchID:"+jsonArray.length()
		                                 +"\nGetting BatchID");
		                for(int i=0;i<jsonArray.length();i++)
		                {
		                    batchID.add(jsonArray.getString(i));
		                }
		            }
				   
				    if(jsonObject.has("MinimumValue"))
		            {
		               jsonArray = jsonObject.getJSONArray("MinimumValue");
		               System.out.println("length of MinimumValue:"+jsonArray.length()
		                                 +"\nGetting MinimumValue");
		                for(int i=0;i<jsonArray.length();i++)
		                {
		                    minVal.add(jsonArray.getString(i));
		                }
		            }
				    
				    if(jsonObject.has("MaximumValue"))
		            {
		               jsonArray = jsonObject.getJSONArray("MaximumValue");
		             
		               for(int i=0;i<jsonArray.length();i++)
		                {
		                    maxVal.add(jsonArray.getString(i));
		                    System.out.println(jsonArray.getString(i));
		                }
		            }
				    
				    if(jsonObject.has("ProductName"))
		            {
		                jsonArray=jsonObject.getJSONArray("ProductName");

		                System.out.println("length of productID:"+jsonArray.length()
		                       +"\nGetting product name");
		                for(int i=0;i<jsonArray.length();i++)
		                {
		                    productName.add(jsonArray.getString(i));
		                }
		            }
				    
				    if(jsonObject.has("ProductType"))
		            {
		                jsonArray=jsonObject.getJSONArray("ProductType");
		                System.out.println("length of productID:"+jsonArray.length()
		                                   +"\nGetting product Type");
		                
		                for(int i=0;i<jsonArray.length();i++)
		                {
		                    productType.add(jsonArray.getString(i));
		                }
		            }
				    if(jsonObject.has("ImageURL"))
		            {
		                jsonArray=jsonObject.getJSONArray("ImageURL");
		                System.out.println("length of ImageURL:"+jsonArray.length()
		                                   +"\nGetting ImageURL");
		                
		                for(int i=0;i<jsonArray.length();i++)
		                {
		                	ImageURL.add(jsonArray.getString(i));
		                }
		            }
				    
				    
				    System.out.println("=================>Printing products");
		             System.out.println("Size:"+productID.size());
		             for(int i=0;i<productID.size();i++)
		             {
		                  System.out.println("SystemServiceID:"+sysSerID.get(i));
		                  System.out.println("SystemServiceName:"+sysSerName.get(i));
		                  System.out.println("ID:"+productID.get(i));
		                  System.out.println("Name:"+productName.get(i));
		                  System.out.println("Produce Desc:"+productDesc.get(i));
		                  System.out.println("Type:"+productType.get(i));
		                  System.out.println("BatchID:"+batchID.get(i));
		                  System.out.println("Minimum value:"+minVal.get(i));
		                  System.out.println("Maximum Value:"+maxVal.get(i));
		                  System.out.println("ImageURL:"+ImageURL.get(i));
		                  System.out.println("=====================");
		             }
		             
		             
		           ArrayList<Products> productList=new ArrayList<Products>();
		             
		           System.out.println("=====================>inserting product indb..");
		           for(int i=0;i<productID.size();i++)
		           {
		        	   
		        	   Products products=new Products();
		               products.setSystemServiceID((String)sysSerID.get(i));
		               products.setSystemServiceName((String)sysSerName.get(i));
		               products.setProductID((String)productID.get(i));
		               products.setProductName((String)productName.get(i));
		               products.setProductDesc((String)productDesc.get(i)); 
		               products.setProductType((String)productType.get(i));
		              // products[i].setProductType("1");
  
		               products.setBatchID((String)batchID.get(i));
		               products.setMinValue((String)minVal.get(i));
		               products.setMaxValue((String)maxVal.get(i));
		               products.setImageURL((String)ImageURL.get(i));
		               
		               //inserting product into Database.   
		               
		                
		               //inserting product into ArrayList
		               productList.add(products);
		           } 
		           
		             return productList;
				}
				else
				{
					handler.post(new Runnable()
					{
						
						public void run() 
						{
							// TODO Auto-generated method stub
							pd.dismiss();
							try 
							{
								Toast.makeText(mContext,jsonObject.getString("ResponseDescription"),Toast.LENGTH_LONG).show();
							}
							catch (JSONException e) 
							{
								e.printStackTrace();
							}
						}
					});
					return null;
				}
			} 
			catch (final JSONException e) 
			{
				handler.post(new Runnable()
				{ 
					public void run() 
					{
						// TODO Auto-generated method stub
						pd.dismiss();
						Toast.makeText(mContext, "JSON Exception:\n"+e.getMessage(),Toast.LENGTH_LONG).show();
					}
				});
				e.printStackTrace();
				return null;
			}
			
	}

	private String createHttpConn() 
	{
		// TODO Auto-generated method stub
		checksumString=userInfo.getLoginID()+"|"+userInfo.getpublickey();
		Log.d("CheckSum",checksumString);
		try
		{
			String checkSum=md5generator.MD5(md5generator.SHA1(checksumString));
	        System.out.println("Final CheckSum:"+checkSum);
	        URL=AppData.hostURL+"/WebService/iTopUp/agentapp.php/ProductDetails/LoginId/"+userInfo.getLoginID()+
                    "/Checksum/"+checkSum;
	        System.out.println("URL:"+URL);
	        
	        String result=httpConn.createHttpConn(URL);
	        return result;
	        
		}
		catch(Exception e)
		{
			handler.post(new Runnable()
			{ 
				public void run() 
				{
					// TODO Auto-generated method stub
					pd.dismiss();
					Toast.makeText(mContext, mContext.getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
				}
			});
			e.printStackTrace();
			Log.d("HTTP Conn Error","Exception found in HttpConn in MyProducts");
			return null;
		}
	}

	private boolean getProductsFromDB() 
	{
		
		if(this.dh.checkProducts()>0)
		{
			return true;
		}
		else
		{
			return false;
		}
//		ArrayList<Products> products = this.dh.selectAll();
 
	}

}
